﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Arroguella.Screens
{
    public class TitleScreen : Screen
    {
        #region Constructor

        public TitleScreen(ContentManager contentMgr, EventHandler theScreenEvent, GraphicsDevice graphicsDevice, Arroguella arroguella)
            : base(theScreenEvent, graphicsDevice, arroguella)
        {
            //Load the background texture for the screen
            try
            {
                Font = contentMgr.Load<SpriteFont>("DefaultSpriteFont");
                Background = contentMgr.Load<Texture2D>("Arroguella Title Screen");
            }
            catch { /* Ignore, continue */ }

            // Load the background music for the screen
            // "Last of the Wilds" originally by Nightwish
            Song titleMusic = contentMgr.Load<Song>("Music/LastOfTheWilds8Bit");

            MediaPlayer.IsRepeating = true;
            MediaPlayer.Volume = 0.1f;
            MediaPlayer.Play(titleMusic);
        }

        #endregion

        #region Events
        #endregion

        #region Methods

        //Update all of the elements that need updating in the Title Screen        
        public override void Update(GameTime theTime)
        {
            KeyboardState keyboardState = Keyboard.GetState(PlayerOne);

            if (keyboardState.IsKeyDown(Keys.Escape))
            {
                MediaPlayer.Stop();
                Arroguella.Exit();
            }

            if (keyboardState.IsKeyDown(Keys.Enter))
            {
                MediaPlayer.Stop();
                ScreenEvent.Invoke(this, new EventArgs());
            }

            base.Update(theTime);
        }

        //Draw all of the elements that make up the Title Screen
        public override void Draw(SpriteBatch spriteBatch)
        {
            DrawBackground(spriteBatch);

            if(Font != null && Background == null)
            {
                string text = "Welcome to Arroguella!\nPress ENTER to continue...";
                Vector2 textSize = Font.MeasureString(text);

                // Find the position for the top left corner of the text, so text is centered
                float textX = TitleSafeArea.Center.X - textSize.X/2; // Width
                float textY = TitleSafeArea.Center.Y - textSize.Y/2; // Height
                Vector2 textPos = new Vector2(textX, textY);

                spriteBatch.DrawString(Font, text, textPos, Color.DarkGreen);
            }

            base.Draw(spriteBatch);
        }

        #endregion

        #region Properties

        protected SpriteFont Font;

        #endregion
    }
}
